package com.apache.funds.service.plugins;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.funds.common.FundsCache;
import com.apache.funds.entity.SvmFlowing;
import com.apache.funds.manager.SvmFlowingManager;
import com.apache.funds.util.Constants;
import com.apache.funds.vo.UserFundsVo;

/**
 * 本类主要涉及业务逻辑<br>
 * 1.内部使用，保存flowing流水明细
 */
public class FundsFlowingSavePlugin implements PluginConnector {
	private Logger log = LoggerFactory.getLogger(getClass());

	private SvmFlowingManager svmFlowingManager;
	protected final String entityName = "com.apache.common.entity.SvmFlowing";

	@Override
	public Object execute(ParamsVo vo) throws Exception {
		ResultEntity entity = new ResultEntity();
		entity.setResult("true");
		entity.setMessage("操作失败");
		entity.setEntity("false");

		ParamsVo<SvmFlowing> voFlowing = vo;
		SvmFlowing flowing = (SvmFlowing) vo.getObj();
		String userId = flowing.getUserId();

		long amount = Long.valueOf(flowing.getAmount());
		if (amount == 0 || amount < 0) {
			log.info("本次操作金额[" + amount + "]，估不保存流水明细");
			entity.setMessage(Constants.Msg.F000+",本次操作金额[" + amount + "]，估不保存流水明细");
			entity.setEntity("true");
		} else {

			//查询余额
			long totalAmount = 0;
			long useAmount = 0;
			UserFundsVo fundVo = FundsCache.getInstance().getBalanCache(userId);
			if (fundVo != null) {
				//1.获取剩余总余额
				totalAmount = fundVo.getAmtTotal();//NumberUtil.add(fundVo.getM1(), fundVo.getM2(), 2);
				//2.获取剩余可用余额；
				useAmount = fundVo.getM1();
			}
			flowing.setLeaveAmount(String.valueOf(totalAmount));
			flowing.setUseAmount(String.valueOf(useAmount));

			log.info("[记录资金操作流水]" + flowing.getUserId() + ",通过" + flowing.getActionType() + "("
					+ flowing.getActionName() + ")；进行[" + flowing.getDirection() + "]操作[" + flowing.getAmount()
					+ "]后，剩余总金额[" + flowing.getLeaveAmount() + "]");

			svmFlowingManager.saveInfo(voFlowing);

			entity.setMessage(Constants.Msg.F000+",流水明细保存完成");
			entity.setEntity("true");
		}
		return entity;
	}

	public void setSvmFlowingManager(SvmFlowingManager svmFlowingManager) {
		this.svmFlowingManager = svmFlowingManager;
	}

}
